package com.example.myapplication12_3;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

// 主活动类，负责处理画板的逻辑
public class MainActivity extends AppCompatActivity {
    private DrawingBoard drawingBoard; // 画板对象
    private static final int PERMISSION_REQUEST_CODE = 123; // 权限请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 设置布局文件

        drawingBoard = findViewById(R.id.drawing_board); // 初始化画板
        Button btnClear = findViewById(R.id.btn_clear); // 清空按钮
        Button btnSave = findViewById(R.id.btn_save); // 保存按钮

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawingBoard.clear(); // 清空画板
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkPermission()) {
                    saveDrawing(); // 保存画板内容
                } else {
                    requestPermission(); // 请求权限
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 0, "黑色"); // 添加黑色选项
        menu.add(0, 2, 0, "红色"); // 添加红色选项
        menu.add(0, 3, 0, "蓝色"); // 添加蓝色选项
        menu.add(0, 4, 0, "绿色"); // 添加绿色选项
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                drawingBoard.setPaintColor(Color.BLACK); // 设置画笔颜色为黑色
                break;
            case 2:
                drawingBoard.setPaintColor(Color.RED); // 设置画笔颜色为红色
                break;
            case 3:
                drawingBoard.setPaintColor(Color.BLUE); // 设置画笔颜色为蓝色
                break;
            case 4:
                drawingBoard.setPaintColor(Color.GREEN); // 设置画笔颜色为绿色
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED; // 检查权限
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                PERMISSION_REQUEST_CODE); // 请求权限
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                          @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                saveDrawing(); // 权限授予后保存画板内容
            } else {
                Toast.makeText(this, "需要存储权限才能保存图片", Toast.LENGTH_SHORT).show(); // 权限被拒绝
            }
        }
    }

    private void saveDrawing() {
        Bitmap bitmap = drawingBoard.getBitmap(); // 获取画板内容
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String fileName = "Drawing_" + timeStamp + ".png"; // 生成文件名

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File file = new File(path, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); // 压缩并保存图片
            fos.close();
            Toast.makeText(this, "图片已保存到: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show(); // 保存成功
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show(); // 保存失败
        }
    }
}